from django.http import JsonResponse
from django.shortcuts import render
from django.views import View
from apps.goods.models import SKU
from apps.users.models import User, Address
import json
import re
from django.contrib.auth import login, authenticate
from django.contrib.auth import logout
from django_redis import get_redis_connection
from apps.carts.utils import merge_cookie_to_redis
# from django.contrib.auth.mixins import LoginRequiredMixin, AccessMixin
from utils.views import LoginRequiredJSONMixin
class UsernameCountView(View):
    def get(self, request, username):
        # if not re.match('[a-zA-Z0-9_-]{5,20}', username):
        #     return JsonResponse({'code': 200, 'errmsg': '用户名不满足需求'})

        count = User.objects.filter(username=username).count()
        return JsonResponse({'code': 0, 'count': count, 'errmsg': 'ok'})


def MobilesCountView(request, mobile):
    # class MobilesCountView(View):
    #     def get(self, request, mobile):
    # mobile= request.GET.get(mobile)
    count = User.objects.filter(mobile=mobile).count()
    return JsonResponse({'code': 0, 'count': count, 'errmsg': 'ok'})


class RegisterView(View):
    def post(self, request):
        data = json.loads(request.body.decode())
        # body_bytes = request.body
        # body_str = body_bytes.decode()
        # body_dict = json.loads(body_str)

        username = data.get('username')
        password = data.get('password')
        password2 = data.get('password2')
        mobile = data.get('mobile')
        # sms_code = body_dict.get('sms_code')
        allow = data.get('allow')

        if not all([username, password, password2, mobile, allow]):
            return JsonResponse({'code': 400, 'errmsg': '参数不全'})
        #     3.2 用户名满足规则，用户名不能重复
        if not re.match('[a-zA-Z_-]{5,20}', username):
            return JsonResponse({'code': 400, 'errmsg': '用户名不满足规则'})

        user = User.objects.create_user(username=username,
                                        mobile=mobile, password=password)

        login(request, user)

        return JsonResponse({'code': 0, 'errmsg': 'ok'})



class LoginView(View):

    def post(self, request):
        # 1, 接受数据
        data = json.loads(request.body.decode())
        username = data.get('username')
        password = data.get('password')
        remembered = data.get('remembered')

        # 打印接收到的数据
        print(f'Received data: username={username}, password={password}, remembered={remembered}')

        # 2, 验证数据
        if not all([username, password]):
            return JsonResponse({'code': 400, 'errmsg': '参数不全'})

        # 确定 我们是根据手机号查询 还是用户名查询
        if re.match('1[3-9]\d{9}', username):
            User.USERNAME_FIELD = 'mobile'
        else:
            User.USERNAME_FIELD = 'username'

        # 打印决定后的USERNAME_FIELD
        print(f'User.USERNAME_FIELD set to: {User.USERNAME_FIELD}')

        # 3, 验证用户名和密码是否正确
        # 我们可以通过模型根据用户名来查询
        # User.objects.get(username=username)

        # 方式2
        from django.contrib.auth import authenticate
        # authenticate 传递用户名和密码
        # 如果用户名和密码正确 则返回 User信息
        # 如果用户名和密码不正确 则返回None
        user = authenticate(username=username, password=password)

        # 打印authenticate的结果
        print(f'Authentication result: {user}')

        if user is None:
            return JsonResponse({'code': 400, 'errmsg': '账号或密码错误'})

        # 4, session
        from django.contrib.auth import login
        login(request, user)
        # 5, 判断是否记住密码
        if remembered is not None:
            # 记住登陆  -- 两周 或者 一个月
            request.session.set_expiry(None)
            pass
        else:
            # 不记住登陆 浏览器关闭 session过期
            request.session.set_expiry(0)

        # 6, 返回响应
        response = JsonResponse({'code': 0, 'errmsg': 'ok'})
        # 为了首页显示用户信息
        merge_cookie_to_redis(request, response)
        response.set_cookie('username', username)

        return response



class LogoutView(View):

    def get(self, request):
        logout(request)

        response = JsonResponse({'code': 0, 'errmsg': 'ok'})
        # 2. 删除cookie信息，为什么要删除了？ 因为前端是根据cookie信息来判断用户是否登陆的
        response.delete_cookie('username')

        return response

    def delete(self, request):
        logout(request)

        response = JsonResponse({'code': 0, 'errmsg': 'ok'})
        # 2. 删除cookie信息，为什么要删除了？ 因为前端是根据cookie信息来判断用户是否登陆的
        response.delete_cookie('username')

        return response



class CenterView(LoginRequiredJSONMixin, View):
    def get(self, request):
        info_data = {
            'username': request.user.username,
            'email': request.user.email,
            'mobile': request.user.mobile,
            'email_active': request.user.email_active,
        }
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'info_data': info_data})
    
class EmailView(LoginRequiredJSONMixin, View):
    def put(self,request):
        data= json.loads(request.body.decode())
        email=data.get('email')
        
        user=request.user
        user.email=email
        user.save()
        from django.core.mail import send_mail
        # subject, message, from_email, recipient_list,
        # subject,      主题
        subject = '美多商城激活邮件'
        # message,      邮件内容
        message = "abc"
        # from_email,   发件人
        from_email = '美多商城<qi_rui_hua@163.com>'
        # recipient_list, 收件人列表
        recipient_list = ['909255613@qq.com']
        # 邮件的内容如果是 html 这个时候使用 html_message
        html_message = "点击按钮进行激活 <a href='http://www.itcast.cn/?token=%s'>激活</a>"
     # send_mail(subject=subject,
        #           message=message,
        #           from_email=from_email,
        #           recipient_list=recipient_list,
        #           html_message=html_message)

        # 邮件的内容如果是 html 这个时候使用 html_message
        # 4.1 对a标签的连接数据进行加密处理
        # user_id=1
        from apps.users.utils import generic_email_verify_token
        token = generic_email_verify_token(request.user.id)

        verify_url = "http://www.meiduo.site:8080/success_verify_email.html?token=%s" % token
        # 4.2 组织我们的激活邮件
        html_message = '<p>尊敬的用户您好！</p>' \
                       '<p>感谢您使用美多商城。</p>' \
                       '<p>您的邮箱为：%s 。请点击此链接激活您的邮箱：</p>' \
                       '<p><a href="%s">%s<a></p>' % (email, verify_url, verify_url)

        # html_message="点击按钮进行激活 <a href='http://www.itcast.cn/?token=%s'>激活</a>"%token

        # send_mail(subject=subject,
        #           message=message,
        #           from_email=from_email,
        #           recipient_list=recipient_list,
        #           html_message=html_message)
        from celery_tasks.email.tasks import celery_send_email
        celery_send_email.delay(
            subject=subject,
            message=message,
            from_email=from_email,
             recipient_list=recipient_list,
           html_message=html_message
        )


        return JsonResponse({'code':0,'errmsg':'ok'})


class EmailVerifyView(View):

    def put(self, request):
        # 1. 接收请求
        params = request.GET
        # 2. 获取参数
        token = params.get('token')
        # 3. 验证参数
        if token is None:
            return JsonResponse({'code': 400, 'errmsg': '参数缺失'})
        # 4. 获取user_id
        from apps.users.utils import check_verify_token
        user_id = check_verify_token(token)
        if user_id is None:
            return JsonResponse({'code': 400, 'errmsg': '参数错误'})
        # 5. 根据用户id查询数据
        user = User.objects.get(id=user_id)
        # 6. 修改数据
        user.email_active = True
        user.save()
        # 7. 返回响应JSON
        return JsonResponse({'code': 0, 'errmsg': 'ok'})
    
class AddressCreateView(LoginRequiredJSONMixin,View):
    def post(self,request):
        data=json.loads(request.body.decode())
        receiver = data.get('receiver')
        province_id = data.get('province_id')
        city_id = data.get('city_id')
        district_id = data.get('district_id')
        place = data.get('place')
        mobile = data.get('mobile')
        tel = data.get('tel')
        email = data.get('email')
        user = request.user
        # 验证忽略
        address = Address.objects.create(
            user=user,
            title=receiver,
            receiver=receiver,
            province_id=province_id,
            city_id=city_id,
            district_id=district_id,
            place=place,
            mobile=mobile,
            tel=tel,
            email=email
        )
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        return JsonResponse({'code': 0, 'errmsg': 'ok', 'address': address_dict})


class AddressView(LoginRequiredJSONMixin, View):

    def get(self,request):
        # 1.查询指定数据
        user = request.user

        addresses = Address.objects.filter(user=user,is_deleted=False)
        # 2.将对象数据转换为字典数据
        address_list= []
        for address in addresses:
            address_list.append({
                "id": address.id,
                "title": address.title, 
                "receiver": address.receiver,
                "province": address.province.name,
                "city": address.city.name,
                "district": address.district.name,
                "place": address.place,
                "mobile": address.mobile,
                "tel": address.tel,
            })
        # 3.返回响应
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'addresses': address_list})

class UserHistoryView(LoginRequiredJSONMixin, View):
    def get(self, request):
        user_id = request.user.id

        redis_client = get_redis_connection('history')
        sku_list = redis_client.lrange(f'history_{user_id}', 0, -1)

        history_list = list()
        for sku_id in sku_list:
            sku = SKU.objects.get(id=sku_id)
            history_list.append({
                'id': sku.id,
                'name': sku.name,
                'default_image_url': sku.default_image.url,
                'price': sku.price
            })
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'skus': history_list})

    def post(self, request):
        # 1.接收请求
        # 2.获取请求参数
        sku_id = json.loads(request.body.decode()).get('sku_id')
        # 3.  验证参数
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return JsonResponse({'code': 400, 'errmsg': '参数错误'})
        user_id = request.user.id
        #  4.  连接redis
        redis_client = get_redis_connection('history')
        # 5.  去重 (先删除这个商品id 数据，再添加就可以了)
        redis_client.lrem(f'history_{user_id}', 0, sku_id)
        # 6.  保存到redis中
        redis_client.lpush(f'history_{user_id}', sku_id)
        # 7.  只保存5条记录
        redis_client.ltrim(f'history_{user_id}', 0, 4)
        # 8.  返回JSON
        return JsonResponse({'code': 0, 'errmsg': 'ok'})
